package com.kang.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.kang.pojo.AjaxResult;
import com.kang.pojo.Audit;
import com.kang.pojo.PurchaseItem;
import com.kang.pojo.PurchaseOrder;
import com.kang.pojo.PurchaseOrderItem;
import com.kang.pojo.PurchaseRequest;
import com.kang.service.AssistService;
import com.kang.service.AuditService;
import com.kang.service.PurchaseOrderService;
import com.kang.service.SupplierService;
import com.kang.service.WarehouseService;
import com.kang.until.FileUtil;
import com.kang.until.PDFUtil;
import com.kang.until.PurchaseAgentPDF;
import com.kang.until.PurchaseOrderPDF;
import com.kang.until.purchaseOrderExcelInput;
import com.vonechina.entity.page.PurchaseOrderPage;

import jxl.Sheet;
import jxl.Workbook;

/**
 * 采购订单控制层
 * 
 * @author zs614
 *
 */
@Controller
@RequestMapping("purchaseOrder")
@SessionAttributes({ "purchaseOrderPage" })
public class PurchaseOrderController extends com.kang.controller.Controller {
	/**
	 * 采购订单服务层
	 */
	@Resource
	private PurchaseOrderService orderService;
	/**
	 * 通用服务层
	 */
	@Resource
	private AssistService assistService;
	/**
	 * 供应商服务层
	 */
	@Resource
	private SupplierService supplierService;
	/**
	 * 仓库服务层
	 */
	@Resource
	private WarehouseService warehouseService;
	/**
	 * 审核服务层
	 */
	@Resource
	private AuditService auditService;

	/**
	 * 查看采购订单分页接口
	 * 
	 * @param session
	 * @param model
	 * @param purchaseOrderPage
	 *            搜错参数自动封装实体类
	 * @return 返回jsp页面
	 */
	@RequestMapping("listPurchaseOrder")
	public String listPurchaseOrder(HttpSession session, Model model, PurchaseOrderPage purchaseOrderPage) {
		initRight(session);
		if (checkRight("查看采购订单") != SUCCESS && checkRight("查看全部采购订单") != SUCCESS) {
			return "basic/noRight";
		}
		if (checkRight("查看全部采购订单") == SUCCESS) {
			purchaseOrderPage.setCreatePersonID(null);
		} else {
			purchaseOrderPage.setCreatePersonID(userID);
		}
		model.addAttribute("orderList", orderService.listPurchaseOrder(purchaseOrderPage));
		purchaseOrderPage.setPageUrl("purchaseOrder/listPurchaseOrder.do");
		model.addAttribute("page", purchaseOrderPage);
		return "business/purchaseOrder/listPurchaseOrder";
	}

	/**
	 * 删除未提交采购订单
	 * 
	 * @param session
	 * @param purchaseOrderID
	 *            采购订单ID
	 * @return 返回json字符串
	 */
	@RequestMapping("delete")
	@ResponseBody
	public String deletePurchaseOrder(HttpSession session, int purchaseOrderID) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		PurchaseOrder order = orderService.selectOrderById(purchaseOrderID);
		if (order.getCreatePersonID() == userID && checkRight("新增采购订单") == SUCCESS) {

		} else if (checkRight("编辑全部采购订单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = orderService.deleteOrder(purchaseOrderID);
		if (a > 0) {
			orderService.deleteOrderAllItem(purchaseOrderID);
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 提交未提交订单
	 * 
	 * @param session
	 * @param purchaseOrderID
	 *            采购订单ID
	 * @return 返回json字符串
	 */
	@RequestMapping("submit")
	@ResponseBody
	public String submitPurchaseOrder(HttpSession session, int purchaseOrderID) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		PurchaseOrder order = orderService.selectOrderById(purchaseOrderID);
		if (order.getCreatePersonID() == userID && checkRight("新增采购订单") == SUCCESS) {

		} else if (checkRight("编辑全部采购订单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = orderService.submitOrder(purchaseOrderID, (Integer) session.getAttribute("userID"));
		if (a > 0) {
			Audit audit = new Audit();
			audit.setAuditType(2);
			audit.setSourceID(purchaseOrderID);
			audit.setLastPersonID(userID);
			audit.setMoney("0");
			auditService.addAudit(audit);
			orderService.updateStatus(purchaseOrderID, 2);
			result.setResult("success");
		}
		return JSON.toJSONString(result);
	}

	/**
	 * 查看采购订单详情
	 * 
	 * @param session
	 * @param model
	 * @param purchaseOrderID
	 *            采购订单ID
	 * @return 返回json字符串
	 */
	@RequestMapping("detail")
	public String purchaseOrderDetail(HttpSession session, Model model, int purchaseOrderID) {
		initRight(session);
		PurchaseOrder order = orderService.selectOrderById(purchaseOrderID);
		if (order.getCreatePersonID() == userID && checkRight("新增采购订单") == SUCCESS) {
			model.addAttribute("isEdit", true);
		} else if (checkRight("编辑全部采购订单") == SUCCESS) {
			model.addAttribute("isEdit", true);
		} else {
			model.addAttribute("isEdit", false);
		}
		order.setShouldPay(orderService.countOrderPrice(order));
		model.addAttribute("order", order);
		model.addAttribute("itemList", orderService.listItemForOrder(purchaseOrderID));
		model.addAttribute("supplierList", supplierService.listAllSupplier());
		model.addAttribute("cruiseList", assistService.listCruise());
		model.addAttribute("organizations", assistService.listOrganization());
		model.addAttribute("warehouseList", warehouseService.listAllWarehouse());
		return "business/purchaseOrder/purchaseOrderDetail";
	}

	/**
	 * 更新采购订单
	 * 
	 * @param session
	 * @param order
	 *            采购订单自动封装啊实体类
	 * @param sourceID
	 *            采购订单物品来源ID
	 * @param itemNumber
	 *            采购订单物品采购数量
	 * @return 返回josn字符串
	 */
	@RequestMapping("update")
	@ResponseBody
	public String updatePurchaseOrder(HttpSession session, PurchaseOrder order, Integer[] sourceID,
			Integer[] itemNumber) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (orderService.selectOrderById(order.getPurchaseOrderID()).getCreatePersonID() == userID
				&& checkRight("新增采购订单") == SUCCESS) {

		} else if (checkRight("编辑全部采购订单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = orderService.updateOrder(order);
		if (a > 0) {
			orderService.saveOrderItem(order.getPurchaseOrderID(), sourceID, itemNumber);
			result.setResult("success");
		}
		return result.toJSONString();
	}

	/**
	 * 更新并提交采购订单
	 * 
	 * @param session
	 * @param order
	 *            采购订单自动封装实体类
	 * @return 返回josn字符串
	 */
	@RequestMapping("updateAndSubmit")
	@ResponseBody
	public String updateAndSubmitPurchaseOrder(HttpSession session, PurchaseOrder order) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (orderService.selectOrderById(order.getPurchaseOrderID()).getCreatePersonID() == userID
				&& checkRight("新增采购订单") == SUCCESS) {

		} else if (checkRight("编辑全部采购订单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		int a = orderService.updateOrder(order);
		a = orderService.submitOrder(order.getPurchaseOrderID(), (Integer) session.getAttribute("userID"));
		if (a > 0) {
			Audit audit = new Audit();
			audit.setAuditType(2);
			audit.setSourceID(order.getPurchaseOrderID());
			audit.setLastPersonID(userID);
			audit.setMoney("0");
			auditService.addAudit(audit);
			orderService.updateStatus(order.getPurchaseOrderID(), 2);
			result.setResult("success");
		}
		return result.toJSONString();
	}

	/**
	 * 结算前获取采购订单信息
	 * 
	 * @param session
	 * @param purchaseOrderID
	 *            采购对订单ID
	 * @return 返回json字符串
	 */
	@RequestMapping("toSettle")
	@ResponseBody
	public String toSettle(HttpSession session, Integer purchaseOrderID) {
		PurchaseOrder order = orderService.selectOrderById(purchaseOrderID);
		order.setShouldPay(orderService.countOrderPrice(order));
		return JSON.toJSONString(order);
	}

	/**
	 * 结算采购订单
	 * 
	 * @param session
	 * @param order
	 *            采购订单实体类自动封装
	 * @return 返回josn字符串
	 */
	@RequestMapping("settle")
	@ResponseBody
	public String settle(HttpSession session, PurchaseOrder order) {
		initRight(session);
		AjaxResult result = new AjaxResult();
		if (orderService.selectOrderById(order.getPurchaseOrderID()).getCreatePersonID() == userID
				&& checkRight("新增采购订单") == SUCCESS) {

		} else if (checkRight("编辑全部采购订单") == SUCCESS) {

		} else {
			result.setResult("noRight");
			return JSON.toJSONString(result);
		}
		order.setSettlePersonID(userID);
		int a = orderService.settleOrder(order);
		if (a > 0) {
			result.setResult("success");
		}
		return result.toJSONString();
	}
	
	/**
	 * 导出采购订单PDF文件
	 * 
	 * @param session
	 * @param response
	 * @param purchaseOrderID
	 *            采购订单ID
	 * @throws Exception
	 */
	@RequestMapping("download")
	public void downloadPDF(HttpSession session, HttpServletResponse response,PurchaseOrder Order, int purchaseOrderID)
			throws Exception {

		PurchaseOrder pcOrder = orderService.selectOrderById(purchaseOrderID);
		List<PurchaseOrderItem> list = orderService.listItemForOrder(purchaseOrderID);
		//此方法为直接下载文件
		File file = PurchaseOrderPDF.buildPurchaseOrderPDF(pcOrder,list);
		if (file.isFile() && file.exists()) {
			try {
				 InputStream fis = new BufferedInputStream(new FileInputStream(file));
				    byte[] buffer = new byte[fis.available()];
				    fis.read(buffer);
				    fis.close();
				    response.reset();
				    //乱码处理
				    //先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称用于浏览器的下载框中自动显示的文件名
				    response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().replaceAll(" ", "").getBytes("utf-8"),"iso8859-1"));
				    response.addHeader("Content-Length", "" + file.length());
				    OutputStream os = new BufferedOutputStream(response.getOutputStream());
				    response.setContentType("application/octet-stream");
				    os.write(buffer);//输出文件
				    os.flush();
				    os.close();//关闭流，释放资源！
			} catch (Exception e) {
				e.printStackTrace();
			}
			file.delete();
		}
	}
	
	
}
